#include<stdio.h>
#include<math.h>
#include<time.h>
#include<SDL2/SDL.h>

void ai_move(SDL_Rect p[])
{
	if(p[1].y > p[2].y) p[1].y-=15;
	if((p[1].y + p[1].h) < p[2].y) p[1].y+=15;
	/*if(p[0].y > p[2].y) p[0].y-=15;
	if((p[0].y + p[0].h) < p[2].y) p[0].y+=15;*/
	if(p[1].y < 10) p[1].y = 10;
	if(p[1].y + p[1].h > 600 - 10) p[1].y = 600 - p[1].h - 10;
	if(p[0].y < 10) p[0].y = 10;
	if(p[0].y + p[0].h > 600 - 10) p[0].y = 600 - p[1].h - 10;

}

double angle_var(SDL_Rect p, SDL_Rect b)
{
	return (double)(b.y - ((p.y + p.h/2)))/50;
}
void ball_setv(double *x, double *y, double v)
{
	*x = cos(v) * sqrt(50);
	*y = sin(v) * sqrt(50);
}

void init_game(SDL_Rect p[], double *ballx, double *bally)
{
	p[0].h = 100;
	p[0].w = 10;
	p[1].h = 100;
	p[1].w = 10;
	p[2].h = 5;
	p[2].w = 5;
	p[0].x = 20;
	p[0].y = 20;
	p[1].x = 800 - 20;
	p[1].y = 20;
	p[2].x = 800 / 2;
	p[2].y = 600 / 2;
	ball_setv(ballx, bally, rand() % 2 - 1);

}

int main(int argc, char *argv[])
{
	SDL_Window *window;
	SDL_Renderer *renderer;
	SDL_Event e;
	SDL_Rect p[3];
	double ballx, bally;
	int playerv = 0;
	srand(time(NULL));
	init_game(p, &ballx, &bally);

	int running = 1;

	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
	window = SDL_CreateWindow("pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_OPENGL);
	renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

	while(running)
	{
		while(SDL_PollEvent(&e))
		{
			switch(e.type)
			{
				case SDL_QUIT:
					running = 0;
					break;
				case SDL_KEYDOWN:
					switch(e.key.keysym.sym)
					{
						case SDLK_UP:
							playerv = -15;
							break;
						case SDLK_DOWN:
							playerv = 15;
							break;
					}
					break;
				case SDL_KEYUP:
					switch(e.key.keysym.sym)
					{
						case SDLK_UP:
							if(playerv = -15) playerv = 0;
							break;
						case SDLK_DOWN:
							if(playerv = 15) playerv = 0;
							break;
					}
							
					break;
			}
		}
		SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
		SDL_RenderClear(renderer);
		SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
		SDL_RenderFillRects(renderer, p, 3);
		SDL_RenderPresent(renderer);
		if((p[2].y >= 600 - 10) || (p[2].y <= 10 ))
		{
			bally= -1 * bally;
			if(p[2].y < 10) p[2].y = 20;
		}
		if((p[2].x >= 800 - 20) && (p[2].y >= p[1].y) && (p[2].y <= p[1].y + p[1].h))
		{
			ball_setv(&ballx, &bally, angle_var(p[1],p[2]));
			if(ballx > 0) ballx = -ballx;
			printf("%f\n%f\n",ballx,bally);
		}
		if((p[2].x <= 20) && (p[2].y >= p[0].y) && (p[2].y <= p[0].y + p[0].h))
		{
			ball_setv(&ballx, &bally, angle_var(p[0],p[2]));
			if(ballx < 0) ballx = -ballx;
			printf("%f\n%f\n",ballx,bally);
		}
		p[2].x += ballx;
		p[2].y += bally;
		p[0].y += playerv;
		ai_move(p);
		SDL_Delay(1000/60);
	}
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);

	SDL_Quit();
	return 0;
}
